import { http } from './http'
import dayjs from 'dayjs'

const host = 'https://movieface.oss-cn-hangzhou.aliyuncs.com/'

export async function upload() {
	return new Promise(async (resolve, reject) => {
		let data = {}

		// 获取签名
		let res = await http.get('/Usersd/getUploadToken')
		if (res.code == 200) {
			data.accessid = res.result.accessid
			data.callback = res.result.callback
			data.dir = res.result.dir
			data.expire = res.result.expire
			data.host = res.result.host
			data.policy = res.result.policy
			data.signature = res.result.signature
		}

		uni.chooseImage({
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: function (res) {
				let path = res.tempFiles[0].name || res.tempFiles[0].path
				let extension = path.split('.')[1]

				let fileRealName = dayjs().format('YYYYMMDDHHMMss') + '.' + extension

				let filename = data.dir + fileRealName

				uni.uploadFile({
					url: host,
					filePath: path,
					name: 'file',
					formData: {
						key: filename,
						OSSAccessKeyId: data.accessid,
						policy: data.policy,
						signature: data.signature,
						expire: data.expire,
					},
					success: (res) => {
						if (res.statusCode === 204) {
							resolve({ success: true, filename: fileRealName })
						} else {
							reject({ success: false, err: res })
						}
					},
					fail: (err) => {
						reject({ success: false, err })
					},
				})
			},
		})
	})
}
